#
#===============================================================================
#
#         FILE:  TVRage.pm
#
#  DESCRIPTION:  
#
#        FILES:  ---
#         BUGS:  ---
#        NOTES:  ---
#       AUTHOR:   (), <>
#      COMPANY:  
#      VERSION:  1.0
#      CREATED:  04/20/2010 06:06:11 PM GMT
#     REVISION:  ---
#===============================================================================

use strict;
use warnings;

package GoogPl::TVRage;

use XML::Simple;
use LWP::UserAgent;
use Time::ParseDate;
use Text::Levenshtein qw(distance);

sub register {
    my $self = shift;

    return ('cmd' => 'tv', 'pat' => '^!tv\s+(.*)');
}

sub help {
    my $self = shift;
    
    return ('Search TV listings and display next episode information.');
}

sub process_command {
    my $self = shift;
    my ($kernel, $sender, $nickhost, $target, $msgtxt, %conf) = @_;

    $msgtxt =~ /^!tv\s+(.*)/;

    my $arg = $1;

    my $ua = LWP::UserAgent->new;

    my $resp = $ua->get("http://services.tvrage.com/feeds/search.php?show=$arg");
    if( ! $resp->is_success ) { return; }
    my $xs = XML::Simple->new;
    my $show_xml = $xs->XMLin($resp->decoded_content);
    if( $show_xml eq '0' ) {
        $kernel->post($sender => privmsg => $target => "No show information found");
        return;
    }

# tvrage search isn't very specific, so we do a little bit of refinement of the
# results to find the best match out of the returned results.
    my $key; my $score = 99;
    foreach my $k (keys %{$show_xml->{'show'}}) {
        if( distance(lc($k), lc($arg)) < $score ) {
            $key = $k;
            $score = distance(lc($k), lc($arg));
        }
    }
    my %show = %{$show_xml->{'show'}{$key}};
    my $id = $show{'showid'};

    $resp = $ua->get("http://services.tvrage.com/feeds/full_show_info.php?sid=$id");
    if( ! $resp->is_success ) { return; }

    my $xml = $xs->XMLin($resp->decoded_content);

    my $seasons = $xml->{'Episodelist'}{'Season'};
    if( ref($seasons) eq 'HASH' ) {
        $seasons = [ $seasons ];
    }
    
    my ($next, $last);
    my $today = parsedate('midnight');
    foreach my $season (@$seasons) {
        foreach my $ep (@{$season->{'episode'}}) {
            my $ts = parsedate($ep->{'airdate'});

            if( $ts > $today ) {
                if( ! defined $next ) {
                    $next = $ep;
                }

                if( $ts < parsedate($next->{'airdate'}) ) {
                    $next = $ep;
                }
            }
            else {
                if( ! defined $last ) {
                    $last = $ep;
                }

                if( $ts > parsedate($last->{'airdate'}) ) {
                    $last = $ep;
                }
            }
        }
    }

    if( ref($next) ) {
            $kernel->post($sender => privmsg => $target => 
                sprintf('%s: next epside on %s: %s ( %s )',
                    $key, $next->{'airdate'},
                    $next->{'title'}, $show{'link'}));
    }
    elsif( ref($last) ) {
            $kernel->post($sender => privmsg => $target => 
                sprintf('%s: last epside on %s: %s ( %s )',
                    $key, $last->{'airdate'},
                    $last->{'title'}, $show{'link'}));
    }
    else {
        $kernel->post($sender => privmsg => $target =>
                sprintf('%s: no episode information ( %s )',
                    $key, $show{'link'}));
    }
}

1;
